<template>
    <div class="message">

        
        <div class="message-tabs">

            <div class="tabs-labels-container">
                <div class="message-tabs-labels">
                    <div v-for="(tab, idx) in tabs" :key="idx" ref="messageTabs" class="message-tabs-label" :class="{ 'active': selected === tab.key }" @click="selectTab( tab.key, tab.name )">
                        <span>{{ tab.name }}</span>
                    </div>
                    <div class="message-tabs-labels-active" :style="activeStyle"></div>
                    <div class="message-read-all" v-if="!!unreadMessage.length" @click="readAll"> 全部标记为已读</div>
                </div>
            </div>

            <div class="message-tabs-panes">
                
                <g-scrollbar class="tabs-panes-scroll">
                    <div class="messages-content">
                        <ul class="message-view">
                            <message-list
                                v-for="(data, index) in currentMessages.messages"
                                :item="data"
                                :index="index"
                                :key="data.uid"
                                v-on:read-message="readMessage"></message-list>
                        </ul>

                        <div class="add-more-wrapper">
                            <button class="add-more" v-show="currentMessages.hasNext" @click="addMore()" :disabled="isLoading">
                                <span v-show="!isLoading">
                                    <i class="iconfont icon-flip-down"></i> 加载更多
                                </span>
                                <span v-show="isLoading">
                                    <i class="iconfont icon-loading spin"></i> 加载中…
                                </span>
                            </button>
                        </div>
                    </div>
                </g-scrollbar>

            </div>

        </div>


    </div>
    
</template>

<script>

import Bus from '@/utils/event_bus.js'
import GScrollbar from '@/components/common/g-scrollbar'
import MessageList from './message-list'
import { getStyle } from '@/utils/dom'
import {group as groupAPI, message as messageAPI} from '@/api'

let unReadPage = 1;
let allPage = 1;
let limit = 24;
export default {
    name: 'Message',
    
    data () {

        let name = this.$route.params.name;
        let tabs = [
            {
                key: 'unread', 
                name: '未读'
            },
            {
                key: 'all',
                name: '全部',
            }
        ];

        let selected = tabs[ 0 ].key;
        if ( !!name && tabs.findIndex( item => item.key === name ) >= 0 ) {
            selected = name;
        }

        return {
            tabs,
            selected,
            tabOffset: 0,
            isLoading: false,
            currentMessages: {},
            allMessage: {
                page: 1,
                status: '',
                messages: [],
                hasNext: false,
            },
            unreadMessage: {
                page: 1,
                status: 0,
                messages: [],
                hasNext: false,
            }
                
        }
    },

    components: {
        GScrollbar,
        MessageList,
    },

    activated () {
        this.$emit( 'on-view-load' );
    },

    beforeRouteLeave ( to, from, next ) {
        window.removeEventListener( 'resize', this.updateTabWidth, false );
        this.$destroy();
        next();
    },

    created () {
        window.addEventListener( 'resize', this.updateTabWidth, false );
    },

    mounted () {
        this.updateTabWidth();

        let name = this.$router.currentRoute.params.name;
        this.currentMessages = this[name + 'Message'];
        this.getMessage();

        Bus.$on('get-new-message', this.update);
        
        let match = this.tabs.find( n => n.key === this.selected);
        if (match.name) {
            Bus.$emit('on-submenu-change', match.name);
        }
    },

    watch: {
        '$route.params.name' ( name ) {

            if ( !!name && this.tabs.findIndex( item => item.key === name ) >= 0 ) {

                this.selected = name;
                
                this.currentMessages = this[name + 'Message'];

                if (!this.currentMessages.messages.length) {
                    this.getMessage()
                }
            }
        }
    },

    computed: {
        activeStyle () {  
            let offset = this.tabs.findIndex( item => item.key === this.selected ) * this.tabOffset;
            return `transform: translateX( ${ offset }px )`;
        },
    },

    methods: {

        updateTabWidth() {
            let dom = this.$refs.messageTabs[ 0 ];
            this.tabOffset = dom.offsetWidth + parseInt( getStyle( dom, 'marginRight' ) ) * 2;
        },

        selectTab ( key, name ) {
            this.$router.replace( { name: 'Message', params: { name: key } } )
            Bus.$emit('on-submenu-change', name);
        },

        update () {
            this.getMessage(1, 0);
        },

        async getMessage (page = this.currentMessages.page, status = this.currentMessages.status) {

            let params = {
                status,
                page,
                limit,
            }
            let result = await messageAPI.list(params);

            if (result.data.code != 0) {
                this.$message.error('加载消息失败');
                return;
            }

            let data = result.data.data;

            let hasNext = !(data.length < limit);
            this.currentMessages.hasNext = hasNext;

            if (page === 1 && status === 0) {
                this.unreadMessage.messages = data;
                return;
            } 

            this.currentMessages.messages = this.currentMessages.messages.concat(data);

        },

        async readMessage (item, index) {

            let result = await messageAPI.update(item.uid);

            if (result.data.code != 0) {
                this.$message.error('操作失败')
                return;
            }

            this.unreadMessage.messages.splice(index, 1);

            Bus.$emit('reset-group')

            if (this.unreadMessage.messages.length === 0) {
                Bus.$emit('all-message-readed');
            }
        },

        async readAll () {

            let result = await messageAPI.updateAll();

            if (result.data.code != 0) {
                this.$message.error('操作失败')
                return;
            }

            this.unreadMessage = [];

            Bus.$emit('all-message-readed');
        },

        addMore () {
            
            if (this.isLoading) return;

            this.currentMessages.page += 1;
            this.getMessage();

        }
    },
}
</script>

<style lang="scss">
@import 'common';
.message {
    width: 100%;
    height: 100%;
    padding: 40px 0 0;
    width: 100%;
        

    @media screen and (max-width: 500px) {
        padding: 17px 17px 0;
        min-width: 340px;
    }

    .message-tabs {
        width: 100%;
        height: 100%;
        overflow: hidden;
        min-width: 600px;
        position: relative;

        .tabs-labels-container {
                padding: 0 40px;
                position: absolute;
                overflow: hidden;
                width: 100%;

            .message-tabs-labels {
                user-select: none;
                width: 100%;
                border-bottom: 2px solid $bdGray;
                position: relative;
                margin-bottom: 20px;

                &::after {
                    @include clearfix();
                }

                .message-tabs-labels-active {
                    position: absolute;
                    bottom: -2px;
                    width: 70px;
                    height: 2px;
                    background-color: $primary;
                    transform: translateX(0);
                    @include transition( transform .3s cubic-bezier(.645,.045,.355,1) );
                }

                .message-tabs-label {
                    float: left;
                    width: 70px;
                    margin: 0 10px;
                    height: 42px;
                    line-height: 42px;
                    text-align: center;
                    cursor: pointer;

                    &.active {
                        color: $primary;
                    }

                    &:first-child {
                        margin-left: 0;
                    }
                }

                .message-read-all {
                    position: absolute;
                    right: 16px;
                    cursor: pointer;
                    font-size: 12px;
                    color: $gray;
                    top: 12px;

                    &:hover {
                        color: $primary;
                    }
                }
            }
        }
        
        

        @media screen and (max-width: 460px) {
            .message-tabs-labels {
                .message-tabs-label {
                    margin: 0 2px;
                }
            }
        }

        .message-tabs-panes {

            max-width: 1300px;
            padding-top: 64px;
            height: 100%;

            .tabs-panes-scroll {
                height: 100%;
            }

            .messages-content {

                width: 100%;
                padding: 0 40px;

                .add-more-wrapper {
                    width: 88px;
                    height: 26px;
                    margin: 36px auto;

                    .add-more {
                        cursor: pointer;
                        border-radius: 12px;
                        color: $gray;
                        font-size: 12px;
                        line-height: 22px;
                        margin: auto;
                        text-align: center;
                        white-space: nowrap;
                        vertical-align: middle;
                        width: 86px;
                        height: 24px;
                        border: 1px solid $bdGray;
                        background-color: transparent;

                        i{
                            font-size: 12px;
                        }

                        &:hover{
                            border: 1px solid darker($bdGray, 10%);
                        }
                    }
                }
            }
        }

    }

}
</style>
